﻿using Microsoft.ClearScript.V8;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace FinalPointSet.Model.Model
{
    /// <summary>
    /// 自定义脚本帮助类
    /// </summary>
    public class RunnableScriptHelper
    {
        /// <summary>
        /// 执行脚本代码
        /// </summary>
        /// <param name="script">执行的脚本</param>
        /// <param name="args">传入的参数</param>
        /// <returns></returns>
        private static string Generate(RunnableScript script, string args)
        {
            using var engine = new V8ScriptEngine();
            engine.Execute(script.Script);
            var runResult = engine.Script.Generate(args);
            string result = $"{runResult.ToString()}";
            //Debug.Print($"RunnableScriptHelper.Generate()={result}");
            return result;
        }

        /// <summary>
        /// 执行脚本代码,若代码报错,不返回异常信息
        /// </summary>
        /// <param name="script">执行的脚本</param>
        /// <param name="args">传入的参数</param>
        /// <returns></returns>
        public static string GenerateWithoutLog(RunnableScript script, string args)
        {
            try
            {
                return Generate(script, args);
            }
            catch (Exception ex)
            {
                Debug.Print($"GenerateWithoutLog, 报错信息:{ex.Message}");
                return "";
            }
        }

        /// <summary>
        /// 执行脚本代码,若代码报错,返回异常信息
        /// </summary>
        /// <param name="script">执行的脚本</param>
        /// <param name="args">传入的参数</param>
        /// <returns></returns>
        public static string GenerateWithLog(RunnableScript script, string args)
        {
            try
            {
                return Generate(script, args);
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        /// <summary>
        /// 判断给定的关键词与脚本名称是否相同
        /// </summary>
        /// <param name="script"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string RepalceStringByScript(string content, List<RunnableScript> scripts)
        {
            foreach (RunnableScript script in scripts)
            {
                string scriptName = "{#" + script.Name + "#}";
                if (content.Contains(scriptName))
                {
                    string value = GenerateWithoutLog(script, string.Empty);
                    content = content.Replace(scriptName, value);
                }
            }
            return content;
        }

        /// <summary>
        /// 将输入参数序列化为json字符串
        /// </summary>
        /// <param name="input"></param>
        /// <param name="extraInput"></param>
        /// <returns></returns>
        public static string SerSerializeInput(string input, Dictionary<string, string>? extraInput)
        {
            string[] args = input.Split(",");
            Dictionary<string, string> dict = [];
            foreach (var item in args)
            {
                string[] param = item.Split('=');
                if (param.Length == 2)
                {
                    dict.Add(param[0], param[1]);
                }
            }
            Dictionary<string, string> unionDict;
            if (extraInput != null)
            {
                unionDict = dict.Union(extraInput).ToDictionary(pair => pair.Key, pair => pair.Value);
            }
            else
            {
                unionDict = dict;
            }
            //序列化为json字符串, 传入js代码
            return JsonConvert.SerializeObject(unionDict);
        }
    }
}
